Option Strict On
Option Explicit On

'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com

Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Security

Namespace WESNet.DNN.Modules.EPrayer
    Partial Class PostEPrayer
        Inherits WESNet.DNN.Modules.EPrayer.EPrayerModuleBase

#Region "Private Members"

        Private _IsModerating As Boolean
        Private _Request As RequestInfo
        Private _Post As PostInfo
        Private _SubjectContactUpdatePanel As System.Web.UI.UpdatePanel

#End Region

#Region "Private Methods"

        Private Sub ShowErrorMessage(ByVal Text As String, ByVal ShowOK As Boolean)
            ShowMessage(Text, "NormalRed", ShowOK)
        End Sub

        Private Sub ShowNormalMessage(ByVal Text As String, ByVal ShowOK As Boolean)
            ShowMessage(Text, "NormalText", ShowOK)
        End Sub

        Private Sub ShowMessage(ByVal Text As String, ByVal CssClass As String, ByVal ShowOK As Boolean)
            If ShowOK Then
                MakeMessageOnlyVisible()
                cmdOK.Visible = True
            Else
                cmdOK.Visible = False
            End If
            trMessage.Visible = True
            lblMessage.CssClass = CssClass
            lblMessage.Text = Text
        End Sub

        Private Sub MakeMessageOnlyVisible()
            tblViewRequest.Visible = False
            tblEditRequest.Visible = False
            tblViewStatus.Visible = False
            tblEditStatus.Visible = False
            tblEditPost.Visible = False
        End Sub

        Private Sub ClearMessage()
            trMessage.Visible = False
            lblMessage.Text = String.Empty
        End Sub

        Private Function LookupSubject(ByVal FullName As String) As Integer
            Dim TotalRecords As Integer
            Dim LastName As String
            Dim FirstName As String

            If Not String.IsNullOrEmpty(FullName) Then
                'lookup subject name in DNN user database

                Dim NameTokens() As String = FullName.Split(" "c)
                If NameTokens.Length >= 2 Then
                    FirstName = NameTokens(0)
                    LastName = NameTokens(1)
                    Dim uc As New DotNetNuke.Entities.Users.UserController
                    Dim DNNUser As DotNetNuke.Entities.Users.UserInfo
                    Dim MatchedUsers As ArrayList = DotNetNuke.Entities.Users.UserController.GetUsersByProfileProperty(PortalId, "Lastname", LastName, 0, 10, TotalRecords)
                    Select Case MatchedUsers.Count
                        Case 0
                            tdNameField.Visible = True
                            tdNameSelect.Visible = False
                        Case 1
                            With CType(MatchedUsers(0), DotNetNuke.Entities.Users.UserInfo)
                                tbAddress.Text = CType(IIf(String.IsNullOrEmpty(.Profile.Unit), "", .Profile.Unit & " "), String) & .Profile.Street
                                tbCity.Text = .Profile.City
                                tbState.Text = .Profile.Region
                                tbZipPlus4.Text = .Profile.PostalCode
                                tbEmail.Text = .Email
                            End With
                            tdNameField.Visible = True
                            tdNameSelect.Visible = False
                        Case Else
                            ddlName.Items.Clear()
                            ddlName.Items.Add(New ListItem(Localize("Multiple_SubjectNames_Found"), "-1"))
                            For Each DNNUser In MatchedUsers
                                ddlName.Items.Add(New ListItem(DNNUser.DisplayName, DNNUser.UserID.ToString))
                            Next
                            ddlName.Items.Add(New ListItem(Localize("None_Of_Above"), "-2"))
                            tdNameField.Visible = False
                            tdNameSelect.Visible = True
                    End Select
                    Return MatchedUsers.Count
                End If
            End If
            Return 0
        End Function

Private Function AppendRemoteAddr(ByVal User As String, ByVal RemoteAddr As String) As String
    Dim s As String = User
    If Regex.Match(RemoteAddr, "^\d{1,3}[:.]\d{1,3}[:.]\d{1,3}[:.]\d{1,3}$").Success Then
         s = s & " [ " & RemoteAddr & "]"
    End If
    Return s
End Function

#End Region

#Region "Event Handlers"

    Protected Sub PostEPrayer_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If DotNetNuke.Framework.AJAX.IsInstalled Then
            DotNetNuke.Framework.AJAX.RegisterScriptManager()
            _SubjectContactUpdatePanel = CType(DotNetNuke.Framework.AJAX.WrapUpdatePanelControl(Me.pnlSubjectContact, True), System.Web.UI.UpdatePanel)
        End If
    End Sub

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                Dim epc As New EPrayerController

                If Not CanPost() Then
                    Response.Redirect(AccessDeniedURL(), True)
                End If

                ' Determine RequestId of E-Prayer to Add or Update (-1 if new Request to add)
                If Not (Request.QueryString("RequestID") Is Nothing) Then
                    RequestID = Int32.Parse(Request.QueryString("RequestID"))
                End If

                ' Determine PostId of E-Prayer post to Add or Update (-1 if new post to add)
                If Not (Request.QueryString("PostID") Is Nothing) Then
                    PostID = Int32.Parse(Request.QueryString("PostID"))
                End If

                If Not Request.QueryString("moderation") Is Nothing Then
                    Moderation = Convert.ToString(Request.QueryString("moderation"))
                End If

                SetActions()

                If Not Page.IsPostBack Then
                    'tblSubjectContact.Visible = False
                    'tdNameSelect.Visible = False
                    With ddlCategory
                        .DataSource = epc.GetCategories(ModuleId)
                        .DataBind()
                        .Items.Insert(0, New ListItem(Localize("Please_Select"), "-1"))
                    End With
                    valCategory.InitialValue = ddlCategory.Items(0).Value

                    With ddlStatus
                        .DataSource = epc.GetStati()
                        .DataBind()
                    End With

                    With ddlChurchRelationship
                        .DataSource = epc.GetChurchRelationships()
                        .DataBind()
                        .Items.Insert(0, New ListItem(Localize("Please_Select"), "-1"))
                    End With

                    With ddlRelationship
                        .DataSource = epc.GetRelationships()
                        .DataBind()
                        .Items.Insert(0, New ListItem(Localize("Please_Select"), "-1"))
                    End With

                    With cblDistribution
                        .DataSource = epc.GetDistributions(ModuleId)
                        .DataBind()
                    End With

                    tblEditPost.Visible = True
                    trEnableSubjectContact.Visible = Not IsAnonymous AndAlso MyConfiguration.EnableSubjectContact

                    If PostAction = Enums.PostActions.NewRequest Then
                        tblViewRequest.Visible = False
                        tblEditRequest.Visible = True
                        lblEditRequest.Text = Localize("plNewRequest")
                        tblViewStatus.Visible = False
                        tblEditStatus.Visible = False
                        lblEditPost.Visible = False
                        trTrack.Visible = Not IsAnonymous AndAlso MyConfiguration.EnableNotification And Not UserInfo.IsTrackingAllPosts
                        ddlStatus.SelectedValue = "1"
                        Dim li As ListItem = ddlExpires.Items.FindByValue(MyConfiguration.RequestLifespan.ToString)
                        If li Is Nothing Then
                            ddlExpires.SelectedIndex = 0
                        Else
                            ddlExpires.SelectedIndex = ddlExpires.Items.IndexOf(li)
                        End If
                    Else
                        _Request = epc.GetRequest(RequestID, UserId, False)
                        If _Request Is Nothing Then
                            Response.Redirect(AccessDeniedURL(String.Format(Localize("No_Access_Invalid_RequestID"), RequestID)), True)
                        Else
                            tblEditRequest.Visible = CanEdit(_Request.CreatedByUserID) And (RequestID = PostID)
                            tblViewRequest.Visible = Not tblEditRequest.Visible
                            tblEditStatus.Visible = CanEdit(_Request.CreatedByUserID)
                            tblViewStatus.Visible = Not tblEditStatus.Visible
                            With _Request
                                rblRequestType.SelectedValue = CType(IIf(.IsPraise, "1", "0"), String)
                                lblRequestType.Text = FormatPrayerOrPraise(.IsPraise)
                                ddlCategory.SelectedValue = .CategoryID.ToString
                                lblCategory.Text = .Category
                                tbSubject.Text = .Subject
                                lblSubject.Text = .Subject
                                ddlChurchRelationship.SelectedValue = .ChurchRelationshipID.ToString
                                lblChurchRelationship.Text = .ChurchRelationship
                                If MyConfiguration.EnableSubjectContact Then
                                    If (Not .SubjectContact Is Nothing) AndAlso .SubjectContact.CanContact Then
                                        cbEnableSubjectContact.Checked = True
                                        tblSubjectContact.Visible = True
                                        With .SubjectContact
                                            tbName.Text = .Name
                                            tbAddress.Text = .Address
                                            tbCity.Text = .City
                                            tbState.Text = .State
                                            tbZipPlus4.Text = .ZipPlus4
                                            tbEmail.Text = .EMail
                                        End With
                                    Else
                                        cbEnableSubjectContact.Checked = False
                                        tblSubjectContact.Visible = False
                                    End If
                                End If
                                ddlStatus.SelectedValue = .StatusID.ToString
                                lblStatus.Text = .Status
                                ddlExpires.SelectedValue = "0"
                                If .Expires = DateTime.MinValue Then
                                    lblExpires.Text = String.Empty
                                Else
                                    If .Expires < Today() Then
                                        lblExpires.Text = .Expires.ToShortDateString() & " " & Localize("Expired")
                                    Else
                                        lblExpires.Text = .Expires.ToShortDateString()
                                        Dim BaseDate As DateTime
                                        If .LastModifiedOnDate = DateTime.MinValue Then
                                            BaseDate = .CreatedOnDate
                                        Else
                                            BaseDate = .LastModifiedOnDate
                                        End If
                                        Dim RequestLifespan As Integer = Convert.ToInt32(DateDiff(DateInterval.Day, BaseDate, .Expires))
                                        For i As Integer = 1 To ddlExpires.Items.Count - 1
                                            If Convert.ToInt32(ddlExpires.Items(i).Value) >= RequestLifespan Then
                                                ddlExpires.SelectedIndex = i
                                                Exit For
                                            End If
                                        Next
                                    End If
                                End If
                                cbIsLocked.Checked = .IsLocked
                                lblIsLocked.Text = CType(IIf(.IsLocked, Localize("Locked"), Localize("Not_Locked")), String)
                                lblBody.Text = .Body 'Server.HtmlEncode(.Body)

                                Dim CreatedByUser As String
                                Dim EditedByUser As String
                                If IsAdministrator Then
                                    If String.IsNullOrEmpty(.LastModifiedByUser) Then
                                        CreatedByUser = AppendRemoteAddr(.CreatedByUser, .RemoteAddr)
                                        EditedByUser = .LastModifiedByUser
                                    Else
                                        CreatedByUser = .CreatedByUser
                                        EditedByUser = AppendRemoteAddr(.LastModifiedByUser, .RemoteAddr)
                                    End If
                                Else
                                    CreatedByUser = .CreatedByUser
                                    EditedByUser = .LastModifiedByUser
                                End If

                                If Not String.IsNullOrEmpty(.SubmittedFor) Then
                                    lblViewCreated.Text = CreatedByUser & " " & Localize("on_behalf_of") & " " & .SubmittedFor & " (" & .CreatedOnDate.ToShortDateString & ")"
                                Else
                                    lblViewCreated.Text = CreatedByUser & " (" & .CreatedOnDate.ToShortDateString & ")"
                                End If
                                If Not String.IsNullOrEmpty(EditedByUser) Then
                                    lblViewEdited.Text = EditedByUser & " (" & .LastModifiedOnDate.ToShortDateString & ")"
                                End If
                            End With
                        End If
                    End If

                    trNotifySubject.Visible = MyConfiguration.EnableSubjectContact AndAlso cbEnableSubjectContact.Checked AndAlso Not PostAction = Enums.PostActions.NewRequest

                    If PostAction = Enums.PostActions.NewRequest Or PostAction = Enums.PostActions.NewUpdate Then
                        Select Case UserInfo.IdentifyBy
                            Case 0
                                lblAuthor.Text = AppendRemoteAddr(UserInfo.Username, Request.ServerVariables("REMOTE_ADDR"))
                            Case 1
                                lblAuthor.Text = AppendRemoteAddr(UserInfo.DisplayName, Request.ServerVariables("REMOTE_ADDR"))
                            Case 2
                                lblAuthor.Text = AppendRemoteAddr(UserInfo.Alias, Request.ServerVariables("REMOTE_ADDR"))
                        End Select
                        trEditor.Visible = False
                        rblRequestType.SelectedValue = "0"
                        cmdDelete.Visible = False
                        If PostAction = Enums.PostActions.NewUpdate Then
                            trTrack.Visible = Not IsAnonymous AndAlso MyConfiguration.EnableNotification And Not UserInfo.IsTrackingAllPosts And Not _Request.IsTracking
                            cbTrack.Checked = _Request.IsTracking
                            Utilities.DistributionCBLSet(cblDistribution, _Request.Distribution)
                            lblEditPost.Text = Localize("plNewUpdate")
                        Else
                            Utilities.DistributionCBLSet(cblDistribution, MyConfiguration.NewPostDefaultDistributions)
                        End If
                    Else
                        If PostAction = Enums.PostActions.EditRequest Then
                            _Post = _Request.Posts(0)
                            lblEditRequest.Text = Localize("plEditRequest")
                            lblEditPost.Visible = False
                        Else
                            _Post = epc.GetPost(PostID)
                            lblEditPost.Text = Localize("plEditUpdate")
                            lblEditRequest.Visible = False
                        End If

                        If _Post Is Nothing Then
                            Response.Redirect(AccessDeniedURL("ePrayer post (" & PostID.ToString & ") deleted or invalid"), True)
                        Else
                            trTrack.Visible = Not IsAnonymous AndAlso MyConfiguration.EnableNotification AndAlso (UserId = _Post.CreatedByUserID) AndAlso (Not _Request.IsTracking)
                            With _Post
                                Dim CreatedByUser As String
                                Dim EditedByUser As String
                                If IsAdministrator Then
                                    If String.IsNullOrEmpty(.LastModifiedByUser) Then
                                        CreatedByUser = AppendRemoteAddr(.CreatedByUser, .RemoteAddr)
                                        EditedByUser = .LastModifiedByUser
                                    Else
                                        CreatedByUser = .CreatedByUser
                                        EditedByUser = AppendRemoteAddr(.LastModifiedByUser, .RemoteAddr)
                                    End If
                                Else
                                    CreatedByUser = .CreatedByUser
                                    EditedByUser = .LastModifiedByUser
                                End If
                                lblAuthor.Text = CreatedByUser & " (" & .CreatedOnDate.ToShortDateString & ")"
                                If String.IsNullOrEmpty(.LastModifiedByUser) Then
                                    trEditor.Visible = False
                                Else
                                    lblEditor.Text = EditedByUser & " (" & .LastModifiedOnDate.ToShortDateString & ")"
                                End If
                                tbSubmittedFor.Text = .SubmittedFor
                                ddlRelationship.SelectedValue = .RelationshipID.ToString
                                teBody.Text = .Body
                                Utilities.DistributionCBLSet(cblDistribution, .Distribution)
                                cbNotifySubject.Checked = .NotifySubject
                                If .Track <> -1 Then
                                    cbTrack.Checked = (.Track = 1)
                                End If
                                cmdSubmit.Text = Localize("cmdUpdate")
                                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdDelete, Localize("msgDeletePost"))
                                cmdDelete.Visible = CanDelete(.CreatedByUserID)
                            End With
                        End If
                    End If
                End If
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click
            Try
                Response.Redirect(ReturnUrl, True)
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdSubmit.Click

            Dim _Body As String
            Dim _Subject As String

            Try
                _Body = Server.HtmlDecode(teBody.Text)
                If _Body.Length = 0 Then
                    ShowErrorMessage(Localize("Body_Empty_Error"), False)
                    Return
                End If
                _Subject = tbSubject.Text

                ' Check _body and subject for cross site scripting
                Dim ps As New PortalSecurity
                _Body = ps.InputFilter(_Body, PortalSecurity.FilterFlag.NoScripting)
                _Subject = ps.InputFilter(_Subject, PortalSecurity.FilterFlag.NoMarkup Or PortalSecurity.FilterFlag.NoScripting Or PortalSecurity.FilterFlag.NoAngleBrackets)

                Dim epc As New EPrayerController

                _Request = New RequestInfo
                _Post = New PostInfo

                With _Request
                    .ModuleID = ModuleId
                    .RequestID = RequestID
                    .IsPraise = rblRequestType.SelectedValue = "1"
                    .CategoryID = Integer.Parse(ddlCategory.SelectedValue)
                    .Subject = _Subject
                    If ddlChurchRelationship.SelectedValue = "-1" Then
                        .ChurchRelationshipID = 0
                    Else
                        .ChurchRelationshipID = Integer.Parse(ddlChurchRelationship.SelectedValue)
                    End If
                    If cbEnableSubjectContact.Checked Then
                        .SubjectContact = New SubjectContactInfo()
                        With .SubjectContact
                            .Name = tbName.Text
                            .Address = tbAddress.Text
                            .City = tbCity.Text
                            .State = tbState.Text
                            .ZipPlus4 = tbZipPlus4.Text
                            .EMail = tbEmail.Text
                        End With
                        If PostAction = Enums.PostActions.NewRequest Then
                            cbNotifySubject.Checked = .SubjectContact.CanContact
                        Else
                            cbNotifySubject.Checked = cbNotifySubject.Checked And .SubjectContact.CanContact
                        End If
                    End If
                    If ddlStatus.SelectedValue = "3" Then    '3 is Withdrawn
                        .Expires = DateAdd(DateInterval.Day, -1.0#, Today())
                    Else
                        If tblEditRequest.Visible Then
                            If ddlExpires.SelectedIndex = 0 Then
                                .Expires = DateTime.MinValue
                            Else
                                .Expires = DateAdd(DateInterval.Day, Convert.ToDouble(ddlExpires.SelectedValue), Today())
                            End If
                        Else
                            Dim OldExpires As DateTime
                            If DateTime.TryParse(lblExpires.Text, OldExpires) Then
                                .Expires = OldExpires
                            Else
                                If MyConfiguration.RequestLifespan = 0 Then
                                    .Expires = DateTime.MinValue
                                Else
                                    .Expires = DateAdd(DateInterval.Day, Convert.ToDouble(MyConfiguration.RequestLifespan), Today())
                                End If

                            End If
                        End If
                    End If
                    .StatusID = Integer.Parse(ddlStatus.SelectedValue)
                    .IsLocked = cbIsLocked.Checked
                End With

                With _Post
                    .SubmittedFor = tbSubmittedFor.Text
                    If ddlRelationship.SelectedValue = "-1" Then
                        .RelationshipID = 0
                    Else
                        .RelationshipID = Integer.Parse(ddlRelationship.SelectedValue)
                    End If
                    .Body = _Body
                    .Distribution = Utilities.DistributionCBLGet(cblDistribution, False)
                    If trTrack.Visible Then
                        If cbTrack.Checked Then
                            .Track = 1
                        Else
                            .Track = 0
                        End If
                    End If
                    .NotifySubject = cbNotifySubject.Checked
                    'If RequestID = -1 Or PostID = -1 Then
                    '    .CreatedByUserID = UserId
                    'Else
                    '    .LastModifiedByUserID = UserId
                    'End If
                    .PostID = PostID
                    .RemoteAddr = Request.ServerVariables("REMOTE_ADDR")
                End With

                If PostAction = Enums.PostActions.NewRequest Or PostAction = Enums.PostActions.NewUpdate Then
                    PostID = epc.AddPost(_Request, _Post, UserId)
                    If PostID = -1 Then
                        ShowErrorMessage(Localize("Add_Post_Error"), True)
                        Exit Sub
                    Else
                        If PostAction = Enums.PostActions.NewRequest Then RequestID = PostID
                    End If
                Else
                    If tblEditRequest.Visible Then
                        epc.UpdateRequest(_Request)
                        tblEditStatus.Visible = False
                    End If
                    epc.UpdatePost(_Post, UserId)
                End If

                If tblEditStatus.Visible Then epc.UpdateRequestStatus(RequestID, _Request.StatusID, _Request.Expires, _Request.IsLocked)

                If ModerationAction = Enums.ModerationActions.EditApprove Then
                    epc.ModerateApprovePost(PostID, UserId)
                End If

                Dim mm As New MailManager(PostAction, PostID, ModerationAction)
                mm.SendMail()

                ' refresh stats
                MyConfiguration.ReloadStats()

                If ModerationAction = Enums.ModerationActions.Submit Then
                    ShowNormalMessage(Localize("Post_Pending_Moderation"), True)
                Else
                    ' Redirect back to the page from which we came or which contained the module
                    Response.Redirect(ReturnUrl, True)
                End If
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        Private Sub cmdDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdDelete.Click
            If PostID <> -1 Then
                Try
                    Dim epc As New EPrayerController()
                    Dim objPost As PostInfo = epc.GetPost(PostID)
                    If CanDelete(objPost.CreatedByUserID) Then
                        Dim mm As New MailManager(Enums.PostActions.Delete, PostID, Enums.ModerationActions.None)
                        mm.SendMail()
                        epc.DeletePost(PostID)
                        ' refresh module settings and configuration caches
                        MyConfiguration.ReloadStats()
                    Else
                        Response.Redirect(AccessDeniedURL(Localization.GetString("No_Delete_Access", LocalResourceFile)), True)
                    End If
                    Response.Redirect(ReturnUrl, True)
                Catch exc As Exception
                    ProcessModuleLoadException(Me, exc)
                End Try
            End If
            Response.Redirect(ReturnUrl, True)
        End Sub

        Protected Sub cbEnableSubjectContact_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbEnableSubjectContact.CheckedChanged
            tblSubjectContact.Visible = cbEnableSubjectContact.Checked
            trNotifySubject.Visible = MyConfiguration.EnableSubjectContact AndAlso cbEnableSubjectContact.Checked AndAlso Not PostAction = Enums.PostActions.NewRequest
            If cbEnableSubjectContact.Checked AndAlso tbSubject.Text <> String.Empty AndAlso tbName.Text = String.Empty Then
                Dim NameTokens() As String = tbSubject.Text.Split(" "c)
                If NameTokens.Length >= 2 Then
                    tbName.Text = NameTokens(0) & " " & NameTokens(1)
                Else
                    tbName.Text = tbSubject.Text
                End If
                btnLookupSubject.Visible = LookupSubject(tbName.Text) = 0
            End If
        End Sub

        Protected Sub btnLookupSubject_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLookupSubject.Click
            LookupSubject(tbName.Text)
        End Sub

        Protected Sub ddlName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlName.SelectedIndexChanged
            If ddlName.SelectedIndex <> -1 Then
                Select Case ddlName.SelectedValue
                    Case "-1"             'No Selection was made
                        Exit Sub
                    Case "-2"             'None of those found were correct - let them enter info manually
                        tdNameSelect.Visible = False
                        tdNameField.Visible = True
                    Case Else             'Selection has been made - get UserInfo and populate contact
                        Dim uc As New DotNetNuke.Entities.Users.UserController
                        Dim UserID As Integer = Integer.Parse(ddlName.SelectedValue)
                        Dim DNNUser As DotNetNuke.Entities.Users.UserInfo = uc.GetUser(PortalId, UserID)
                        If Not DNNUser Is Nothing Then
                            With DNNUser
                                tbName.Text = .DisplayName
                                tbAddress.Text = CType(IIf(String.IsNullOrEmpty(.Profile.Unit), "", .Profile.Unit & " "), String) & .Profile.Street
                                tbCity.Text = .Profile.City
                                tbState.Text = .Profile.Region
                                tbZipPlus4.Text = .Profile.PostalCode
                                tbEmail.Text = .Email
                            End With
                            tdNameSelect.Visible = False
                            btnLookupSubject.Visible = True
                            tdNameField.Visible = True
                        End If
                End Select
            End If
        End Sub

        Protected Sub cmdOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOK.Click
            Try
                ' Redirect back to the page from which we came or which contained the module
                Response.Redirect(ReturnUrl, True)
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub
#End Region
    End Class
End Namespace